package org.example.MedicalCrowdsourcing.controller;

import org.example.MedicalCrowdsourcing.dto.ProfileUpdateRequest;
import org.example.MedicalCrowdsourcing.dto.UserDto;
import org.example.MedicalCrowdsourcing.model.entity.LoginRecord;
import org.example.MedicalCrowdsourcing.model.entity.Role;
import org.example.MedicalCrowdsourcing.model.entity.User;
import org.example.MedicalCrowdsourcing.model.CommonResponse;
import org.example.MedicalCrowdsourcing.repository.RoleRepository;
import org.example.MedicalCrowdsourcing.service.PermissionService;
import org.example.MedicalCrowdsourcing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/medical-crowdsourcing/users")
@CrossOrigin(origins = "http://localhost:8081", allowCredentials = "true")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionService permissionService;

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<UserDto> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        User user = userService.findByUsername(userDetails.getUsername())
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        UserDto userDto = convertToDto(user);
        return ResponseEntity.ok(userDto);
    }

    /**
     * 更新用户个人资料
     */
    @PutMapping("/profile")
    public ResponseEntity<UserDto> updateProfile(@RequestBody ProfileUpdateRequest profileRequest) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        User user = userService.findByUsername(userDetails.getUsername())
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 更新用户信息
        if (profileRequest.getEmail() != null && !profileRequest.getEmail().isEmpty()) {
            user.setEmail(profileRequest.getEmail());
        }
        
        if (profileRequest.getBlockchainAddress() != null && !profileRequest.getBlockchainAddress().isEmpty()) {
            user.setBlockchainAddress(profileRequest.getBlockchainAddress());
        }
        
        User updatedUser = userService.save(user);
        UserDto userDto = convertToDto(updatedUser);
        return ResponseEntity.ok(userDto);
    }

    /**
     * 获取用户登录历史
     */
    @GetMapping("/login-history")
    public ResponseEntity<List<Map<String, Object>>> getLoginHistory() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        User user = userService.findByUsername(userDetails.getUsername())
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        List<LoginRecord> loginRecords = userService.getRecentLoginHistory(user);
        
        // 转换为简单的Map输出
        List<Map<String, Object>> result = new ArrayList<>();
        for (LoginRecord record : loginRecords) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", record.getId());
            recordMap.put("loginTime", record.getLoginTime());
            recordMap.put("ipAddress", record.getIpAddress());
            recordMap.put("userAgent", record.getUserAgent());
            recordMap.put("successful", record.isSuccessful());
            result.add(recordMap);
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取所有用户列表
     */
    @GetMapping("/list")
    public ResponseEntity<Object> getAllUsers() {
        List<User> users = userService.findAll();
        
        // 转换为简化的用户信息列表
        List<Map<String, Object>> userList = users.stream().map(user -> {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("email", user.getEmail());
            userMap.put("role", user.getRole().getName());
            userMap.put("blockchainAddress", user.getBlockchainAddress());
            userMap.put("createdAt", user.getCreatedAt());
            userMap.put("lastLogin", user.getLastLogin());
            return userMap;
        }).collect(Collectors.toList());
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取用户列表成功", userList);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取单个用户详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Object> getUserById(@PathVariable Long id) {
        Optional<User> userOpt = userService.findById(id);
        if (!userOpt.isPresent()) {
            CommonResponse response = new CommonResponse("404", "用户不存在", null);
            return ResponseEntity.ok(response);
        }
        
        User user = userOpt.get();
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("email", user.getEmail());
        userInfo.put("role", user.getRole().getName());
        userInfo.put("blockchainAddress", user.getBlockchainAddress());
        userInfo.put("createdAt", user.getCreatedAt());
        userInfo.put("lastLogin", user.getLastLogin());
        
        // 获取用户权限
        Integer roleId = user.getRole().getId();
        List<String> permissions = permissionService.getRolePermissions(roleId);
        userInfo.put("permissions", permissions);
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取用户详情成功", userInfo);
        return ResponseEntity.ok(response);
    }

    /**
     * 更新用户角色
     */
    @PutMapping("/{id}/role")
    public ResponseEntity<Object> updateUserRole(@PathVariable Long id, @RequestParam Integer roleId) {
        Optional<User> userOpt = userService.findById(id);
        Optional<Role> roleOpt = roleRepository.findById(roleId);
        
        if (!userOpt.isPresent() || !roleOpt.isPresent()) {
            CommonResponse response = new CommonResponse("404", "用户或角色不存在", null);
            return ResponseEntity.ok(response);
        }
        
        User user = userOpt.get();
        user.setRole(roleOpt.get());
        userService.save(user);
        
        CommonResponse response = new CommonResponse(CommonResponse.OK, "更新用户角色成功", null);
        return ResponseEntity.ok(response);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Object> deleteUser(@PathVariable Long id) {
        Optional<User> userOpt = userService.findById(id);
        if (!userOpt.isPresent()) {
            CommonResponse response = new CommonResponse("404", "用户不存在", null);
            return ResponseEntity.ok(response);
        }
        
        userService.delete(userOpt.get());
        CommonResponse response = new CommonResponse(CommonResponse.OK, "删除用户成功", null);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取所有角色
     */
    @GetMapping("/roles")
    public ResponseEntity<Object> getAllRoles() {
        List<Role> roles = roleRepository.findAll();
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取角色列表成功", roles);
        return ResponseEntity.ok(response);
    }

    /**
     * 获取角色权限
     */
    @GetMapping("/roles/{roleId}/permissions")
    public ResponseEntity<Object> getRolePermissions(@PathVariable Integer roleId) {
        List<String> permissions = permissionService.getRolePermissions(roleId);
        CommonResponse response = new CommonResponse(CommonResponse.OK, "获取角色权限成功", permissions);
        return ResponseEntity.ok(response);
    }

    /**
     * 将User实体转换为UserDto
     */
    private UserDto convertToDto(User user) {
        return UserDto.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .role(user.getRole().getName())
                .blockchainAddress(user.getBlockchainAddress())
                .createdAt(user.getCreatedAt())
                .lastLogin(user.getLastLogin())
                .build();
    }
} 